package com.itheima.web.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.Route;
import com.itheima.factory.BeanFactory;
import com.itheima.service.RouteService;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/routeServlet")
public class RouteServlet extends BeanServlet {
    RouteService routeService = (RouteService) BeanFactory.getBean("routeService");


    private void routeFindByCid(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String cidStr = req.getParameter("cid");
        int cid = Integer.parseInt(cidStr);
        String pageNumStr = req.getParameter("pageNum");
        String pageSizeStr = req.getParameter("pageSize");
        System.out.println(pageSizeStr);
        if (pageNumStr==null || pageNumStr==""){
            pageNumStr = "1";
        }
        if (pageSizeStr==null || pageSizeStr==""){
            pageSizeStr = "5";
        }
        int pageNum = Integer.parseInt(pageNumStr);
        int pageSize = Integer.parseInt(pageSizeStr);
        PageInfo<Route> pageInfo = routeService.routeFindByCid(cid,pageNum,pageSize);
        System.out.println(pageInfo.toString());
        String value = new ObjectMapper().writeValueAsString(pageInfo);
        resp.getWriter().write(value);
    }

    private void findRouteByRid(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String ridStr = req.getParameter("rid");
        int rid = Integer.parseInt(ridStr);
        Route route = routeService.findRouteByRid(rid);
        String value = new ObjectMapper().writeValueAsString(route);
        resp.getWriter().write(value);
    }

}
